package control

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"gorm/model"
	"net/http"
	"strconv"
)


func getArticle(c *gin.Context)  {
	page := c.DefaultQuery("page","1");
	size := c.DefaultQuery("size","10");
	p, _ := strconv.Atoi(page)
	s, _ := strconv.Atoi(size)

	article, err := model.GetArticle(p,s)

	if err != nil && err!=gorm.ErrRecordNotFound {
		c.JSON(http.StatusOK,gin.H{
			"code":"-1",
			"msg":err.Error(),
		})
		return
	}
	count, err := model.GetArticleCount()
	if err != nil {
		c.JSON(http.StatusOK,gin.H{
			"code":"-1",
			"msg":err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK,gin.H{
		"code":0,
		"data":gin.H{
			"list":article,
			"count":count,
		},
		"msg":"获取成功",
	})
	return

}

func createArticle(c *gin.Context)  {
	userId , _ := c.Get("userId");
	i := userId.(int64)
	articleCount := model.ArticleDb{};
	articleCount.UserId=i;
	err := c.ShouldBind(&articleCount);
	if err != nil {
		c.JSON(http.StatusOK,gin.H{
			"code":-1,
			"msg":err.Error(),
		})
		return
	}
	err = model.CreateArticle(articleCount);
	if err != nil {
		c.JSON(http.StatusOK,gin.H{
			"code":-1,
			"msg":err,
		})
		return
	}
	c.JSON(http.StatusOK,gin.H{
		"code":0,
		"msg":"创建成功",
	})
	return
}

func likeArticle(c *gin.Context)  {
	like := model.LikeDb{}
	userId , _ := c.Get("userId");
	i := userId.(int64)
	articleId := c.PostForm("articleId")
	likeId, err := strconv.ParseUint(articleId,10,64)
	if err != nil {
		c.JSON(http.StatusOK,gin.H{
			"code":-1,
			"msg":err.Error(),
		})
		return
	}
	like.UserId=i;
	like.LikeId=likeId;
	checkLike, err := model.CheckLike(i, likeId)
	if err != nil {
		c.JSON(http.StatusOK,gin.H{
			"code":-1,
			"msg":err.Error(),
		})
		return
	}
	fmt.Println(checkLike)

	if checkLike.ID==0 {
		err = model.LikeArticle(like)
		c.JSON(http.StatusOK,gin.H{
			"code":0,
			"msg":"点赞成功",
		})
		return
	}

	if checkLike.ID>0 {
		c.JSON(http.StatusOK,gin.H{
			"code":-1,
			"msg":"已经点过赞了",
		})
		return
	}
}